﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Drawing;
using org.project.web.utils;
using System.Configuration;
using System.Text;
using System.Data;

public partial class negotiation : System.Web.UI.Page
{
    public volatile String ConnectionString = ConfigurationManager.ConnectionStrings["projectConnectionString"].ConnectionString;
    private String GPServName = "";

    protected void Page_PreInit(object sender, EventArgs e)
    {
        if (Session["MId"] == null)//會員
        {
            this.Page.MasterPageFile = "~/MasterPage.master";
            Response.Redirect("login.aspx");
        }
        else       //一般使用者
            this.Page.MasterPageFile = "~/LoginedMasterPage.master";
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        NDealDateCalendar.TodaysDate = DateTime.Now;
        NGYearTextBox.Text = Convert.ToString(DateTime.Now.Year);
        NDateTextBox.Text = DateTime.Now.ToShortDateString();

        //驗證
        NGYearTextBoxRangeValidator.MaximumValue = Convert.ToString(DateTime.Now.Year);
        NGBudgetRangeValidator.MaximumValue = Convert.ToString(int.MaxValue);

        //NDateTextBox.Text = Convert.ToString(DateTime.Now.ToShortDateString());

        NDealDateRangeValidator.MinimumValue = DateTime.Now.ToShortDateString();

        NDealDateRangeValidator.MaximumValue = DateTime.MaxValue.ToShortDateString();

        NDealDateCalendar.SelectedDate = DateTime.Now.AddDays(1);

        //WEndTextBox.Text = Convert.ToString(DateTime.Now.AddDays(3));

        String MId = Session["MId"].ToString();

        String WId = Session["WId"].ToString();
        String NGName = Session["WGName"].ToString();
        String NGBrand = Session["WGBrand"].ToString();
        
        //String WId = Session["WId"].ToString();

        //String WTran = Session["WTran"].ToString();
        //String WVisible = Session["WVisible"].ToString();
        //String NGApp = Session["WGApp"].ToString();
        //String NGDescription = Session["WGDescription"].ToString();

        //String WGYear = Session["WGYear"].ToString();
        String NGMadeIn = Session["WGMadeIn"].ToString();
        String NGBudget = Session["WGBudget"].ToString();
        //String WNote = Session["WNote"].ToString();
        String NGPId = Session["WGPId"].ToString();
        String GCthird = Session["GCthird"].ToString();
        String HCName = Session["HCName"].ToString();
        String GPServName = Session["GPServName"].ToString();

        MNameTextBox.Text = Session["User"].ToString();
        WIdTextBox.Text = WId;
        
        NGNameTextBox.Text = NGName;
        NGBrandTextBox.Text = NGBrand;
        //NGAppTextBox.Text = NGApp;
        //NGDescriptionTextBox.Text = NGDescription;
        //NGYearTextBox.Text = WGYear;
        NGMadeInTextBox.Text = NGMadeIn;
        //買家預算
        WGBudgetTextBox.Text = NGBudget;
        //GCIdDropDownList.SelectedValue;

        //int GCId = Convert.ToInt32(GCIdDropDownList.SelectedValue);

        //接收到Sesssion 傳遞過來的參數之後，再資料填寫到TextBox 裡面


    }
    protected void SubmitButton_Click(object sender, EventArgs e)
    {
        try
        {
            if (savefile(PictureFileUpload) != true)
            {
                Label1.Text = "您沒有指定檔案";
            }


        }
        catch (Exception ex) {
            Label1.Text = "發生錯誤: " + ex.Message;
        }

        //無上傳圖片
        int NGPId = 1;

        if (!GPServName.Equals(""))
        {

            SQLUtility prequery_utiity = new SQLUtility();

            String GoodsPicSqlQuery = "Select * from GoodsPic Where GPServName ='" + GPServName + "'";

            List<Dictionary<String, Object>> result = prequery_utiity.ExecuteCommand(ConnectionString, GoodsPicSqlQuery);

            /*
            //Single() --> (閉包的其中一種方法之一)
            //ElementAt()--> Enumerable
            */
            NGPId = Convert.ToInt32(result.Single().ElementAt(0).Value);
        }


            //將通緝令新增到資料庫
            //MyWantedSqlDataSource.InsertCommand = 
            SQLUtility utility = new SQLUtility();

            ListItemCollection items = NTranListBox.Items;
            StringBuilder content = new StringBuilder();
            for (int i = 0; i < items.Count; i++)
            {
                if (items[i].Selected)
                {
                    content.Append(items[i].Value);
                    content.Append("、");
                }
            }

            String NTran = content.ToString();

            String NDate = DateTime.Now.ToShortDateString();
            
            /**
             * 
            String WEnd = DateTime.Now.AddDays(3).ToShortDateString();
            */

            //String MId = "1";
            //預設狀態 (交涉中)
            String HCId = "1";
            String NVisible = "true";

            //String GCId = GCThirdDropDownList.SelectedValue;

            //從資料庫查詢到的 GPId
            //WGPId = "3";
            String MId = Session["MId"].ToString();
            String WId = WIdTextBox.Text;

            String NGApp = NGAppTextBox.Text;
            String NGAmount = NGAmountTextBox.Text;
            String NGName = NGNameTextBox.Text;
            String NGDescription = NGDescriptionTextBox.Text;
            int year = Convert.ToInt32(NGYearTextBox.Text);
            //int month = Convert.ToInt32(NGMonthTextBoxDropDownList.SelectedValue);

            //String WGYear = new DateTime(year,month, 1).ToShortDateString();
            int month = Convert.ToInt32(NGMonthTextBoxDropDownList.Text);
            String NGYear = (NGYearTextBox.Text + NGMonthTextBoxDropDownList.Text);
            NGYear = new DateTime(year, month, 1).ToShortDateString();


            String NGBrand = NGBrandTextBox.Text;
            String NGMadeIn = NGMadeInTextBox.Text;
            String NGBudget = NGBudgetTextBox.Text;
            String NDealDate = NDealDateTextBox.Text;

            String NNote = "";

            int GCId = Convert.ToInt32(GCIdDropDownList.SelectedValue);


            String insertNegotiationSql = "INSERT INTO Negotiation(WId, NDate, MId, NDealDate, NVisible, GCId, NGPId, NGApp, NGAmount, NGName, NGDescription, NGYear, NGBrand, NGMadeIn, NGBudget, NNote, NTran)"
                                                   +" VALUES ('" + WId + "','" + NDate + "','" + MId + "','" + NDealDate +"','" + NVisible + "','" + GCId +"','" + NGPId + "','" +NGApp +"','" + NGAmount + "','"
                                                                 + NGName + "','" + NGDescription + "','" + NGYear + "','" + NGBrand + "','" + NGMadeIn + "','" + NGBudget + "','" + NNote + "','" + NTran + "')";

            /*
            String insertWantedSql = "INSERT INTO Wanted(WStart, WEnd, MId, HCId, WTran, WVisible, GCId, WGPId, WGApp, WGAmount, WGName, WGDescription, WGYear, WGBrand, WGMadeIn, WGBudget, WNote)"
                                             + " VALUES ('" + WStart + "','" + WEnd + "','" + MId + "','" + HCId + "','" + WTran + "','" + WVisible + "','" + GCId + "','" + WGPId + "','" + WGApp + "','" + WGAmount + "','" + WGName + "','" + WGDescription + "','" + WGYear + "','" + WGBrand + "','" + WGMadeIn + "','" + NGBudget + "','" + WNote + "')";
            */
            String queryNegotiationSql = "Select * from Negotiation Where MId=" + MId;
            
            int insertRows = utility.ExecuteCommandNonQuery(ConnectionString, insertNegotiationSql);

            /*
            DataSet dataset = new DataSet();
            utility.UseSqlDataAdapterExecuteCommand(ConnectionString, queryNegotiationSql, ref dataset);
            WantedGridView.DataSource = dataset;
            WantedGridView.DataBind();
            */

            Response.Write("<script >alert('新增交涉發布成功！');</script>");
            Response.Redirect("hunter.aspx");
            
    }
    bool savefile(FileUpload Uploading)
    {
        //若有檔案即進行存檔
        if (Uploading.HasFile == true)
        {
            //=================== 處理上傳檔案 ===================

            //ServerFilename 變數為照片在伺服器上的檔名
            string ServerFilename;
            //ServerPathFilename 變數為照片在伺服器上的絕對路徑
            string ServerPathFilename;

            //Guid 類別的 NewGuid 方法可產生具唯一性的字串, 作為照片的檔名
            //System.IO.Path.GetExtension 方法可取得上傳檔案的副檔名
            ServerFilename = Guid.NewGuid().ToString() +
               System.IO.Path.GetExtension(Uploading.FileName).ToLower();

            //Page.MapPath() 方法可以取得檔案或目錄在伺服器上的絕對路徑
            ServerPathFilename = Page.MapPath("~/photo/") + ServerFilename;

            //將上傳的檔案儲存到 ServerPathFilename 所指定的路徑
            Uploading.SaveAs(ServerPathFilename);

            //加總上傳的檔案數及檔案位元組


            //=================== 製作縮圖 ===================

            //縮圖寬高上限
            int MaxLength = 200;
            //縮圖寬度
            int ThumbWidth;
            //縮圖高度
            int ThumbHeight;

            //以 System.Drawing.Image 類別建立 Photo 物件, 
            //然後將原始圖讀入 Photo 物件
            System.Drawing.Image Photo = System.Drawing.Image.FromFile(ServerPathFilename);

            //計算縮圖的寬度與高度
            if (Photo.Width > Photo.Height)
            {
                ThumbWidth = MaxLength;
                ThumbHeight = Convert.ToInt32(Convert.ToSingle(Photo.Height) / Convert.ToSingle(Photo.Width) * MaxLength);
            }
            else
            {
                ThumbHeight = MaxLength;
                ThumbWidth = Convert.ToInt32(Convert.ToSingle(Photo.Width) / Convert.ToSingle(Photo.Height) * MaxLength);
            }

            //以 Bitmap 類別建立 Thumb 物件, 以存放縮圖
            Bitmap Thumb = new Bitmap(Photo, ThumbWidth, ThumbHeight);

            //將縮圖儲存到伺服器上
            Thumb.Save(Page.MapPath("~/thumb/") + ServerFilename);

            //=================== 寫入資料庫 ===================

            //將伺服器檔名與照片名稱指定給 SqlDataSource1 Insert 陳述式的參數
            GCPic.InsertParameters["GPServName"].DefaultValue = ServerFilename;
            GCPic.InsertParameters["GPName"].DefaultValue = Uploading.FileName;

            //將圖片名稱先用變數暫存，之後要新增通緝令時一用這個查詢到它的 GPId 才能一起新增到通緝令的資料表格
            GPServName = GCPic.InsertParameters["GPServName"].DefaultValue;
            
            //將伺服器檔名與照片名稱寫入資料庫
            GCPic.Insert();

            return true;
        }
        else
        {
            return false;
        }
    }

    protected void NDealDateCalendar_SelectionChanged(object sender, EventArgs e)
    {
        DateTime NDealDate = NDealDateCalendar.SelectedDate;
        if (NDealDate.ToShortDateString().CompareTo(DateTime.Now.ToShortDateString())>=0)
        {
            
            
        }
        else {
            NDealDateTextBox.Text = "";

            Response.Write("<script >alert('預定出貨日期必須設定為今天之後.(含今天)');</script>");
        }
        NDealDateTextBox.Text = NDealDate.ToShortDateString();
        
    }
    protected void NDealDateTextBox_TextChanged(object sender, EventArgs e)
    {
        NDealDateRangeValidator.Validate();
    }
}